<template>
  <el-row>
    <el-col :span="18">
      <el-select
              placeholder="选择媒资类型"
              clearable
              size="mini"
              v-model="selectedMediatype"
              class="input-w mr10"
              @change="handleSelectMediatype"
              >
        <el-option
                v-for="mediatype in mediatypeList"
                :key="mediatype.mediatype"
                :label="mediatype.name"
                :value="mediatype.mediatype"
        />
      </el-select>
      <!--<el-select
              placeholder="选择一级分类"
              clearable
              v-model="queryList.catid"
              class="input-w mr10"
              size="mini"
              @change="handleFilterMedia"
      >
        <el-option
                v-for="cate in categoryList"
                :key="cate.catid"
                :label="cate.name"
                :value="cate.catid"
        />
      </el-select>-->
      <el-autocomplete
              placeholder="请输入媒资名称"
              v-model.trim="queryList.keyword"
              size="mini"
              clearable
              class="input-w mr10"
              value-key="name"
              :fetch-suggestions="handleMediaSearchSuggest"
              :trigger-on-focus="false"
              :highlight-first-item="true"
              @select="handleFilterMedia"
              @clear="handleFilterMedia"
      />
      <el-button type="primary" size="mini" @click="handleFilterMedia">
        <el-icon>
          <search />
        </el-icon>
        搜索
      </el-button>
    </el-col>
    <el-col :span="6">
      <div align="right">
        <el-button type="danger" size="mini" @click="batchDeleteMedias">
          <el-icon>
            <delete/>
          </el-icon>
          删除
        </el-button>
        <el-button type="primary" size="mini" @click="handleAddMedias">
          <el-icon>
            <plus />
          </el-icon>
          添加
        </el-button>
      </div>
    </el-col>
    <el-col :span="24" class="mt10">
      <el-table
              ref="mediaDataRef"
              :data="tableData.listData"
              v-loading="isloading"
              border
              style="width: 100%"
              max-height="400px"
              @select="handleSelectMedia"
              @select-all="handleSelectAllMedia"
              @row-click="handleClickRowMedia"
      >
        <el-table-column type="selection" width="40" :selectable="handleSelectMediaAble"/>
        <el-table-column label="缩略图" width="60px">
          <template #default="{row}">
            <span @click.stop>
              <el-image
                      v-if="row.covers && row.covers.length > 0"
                      :src="row.covers[0].isself == 1 ? row.covers[0].viewurl + '&width=60px' : row.covers[0].viewurl"
                      :preview-src-list="imgSrcList"
                      :initial-index="initialIndex(row.covers[0].viewurl)"
              />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="媒资ID" width="80px" align="center" prop="mediaid"></el-table-column>
        <el-table-column label="媒资名称" show-overflow-tooltip>
          <template #default="{row}">
            <a href="javascript:;" class="txttdellipsis" @click.stop="handleToMediaDetail(row)">
              <span v-if="row.highlight && row.highlight.name" v-html="row.highlight.name"></span>
              <span v-else>{{row.name}}</span>
            </a>
          </template>
        </el-table-column>
        <el-table-column label="媒资类型" prop="mediatypename"></el-table-column>
        <el-table-column label="媒资分类" prop="catname"></el-table-column>
        <el-table-column label="来源企业">
          <template #default="{row}">
            <span v-if="currentCorpid != row.corpid && corpPartnerObj[row.corpid] != undefined">{{corpPartnerObj[row.corpid]}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" :sortable="true" width="180px">
          <el-table-column label="修改时间" :sortable="true">
            <template #default="{row}">
              <div>{{row.ctime ? row.ctime.replace('T', ' ') : '--'}}</div>
              <div>{{row.mtime ? row.mtime.replace('T', ' ') : '--'}}</div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="状态" :sortable="true" prop="inuse">
          <template #default="{row}">
            <el-tag type="success" size="mini" v-if="row.inuse == 1">上线</el-tag>
            <el-tag type="danger" size="mini" v-else>下线</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <span v-if="currentCorpid == row.corpid">
              <el-button type="text" size="mini" @click.stop="handleUpdateMedia(row)">编辑</el-button>
              <el-button type="text" size="mini" style="color: red" @click.stop="handleDeleteMedia(row)">删除</el-button>
            </span>
            <span v-else>
              <el-button type="text" size="mini" disabled>编辑</el-button>
              <el-button type="text" size="mini" disabled>删除</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="24" class="mt10">
      <table-pagination
              :query-list="queryList"
              :total="tableData.total"
              @pagination="getMediaList"
      />
    </el-col>
  </el-row>
  <media-dialog
          :packageid="packageid"
          title="媒资列表"
          :visible="addMediaDialogVisible"
          @cancelDialog="cancelDialog"
          @getData="getMediaList"
  />
</template>

<script>
  import {reactive, ref, computed, nextTick} from 'vue'
  import {useRoute, useRouter} from 'vue-router'
  import {useStore} from 'vuex'
  import {getMediaTYpe} from "@/api/media/mediatype";
  // import {getCategories} from "@/api/media/constant";
  import {mediaSearchSuggest, getSearchMediaList} from "@/api/package/project";
  import {Search, Delete, Plus} from '@element-plus/icons'
  import {getCorpPartner} from "@/api/corppartner";
  import TablePagination from "@/views/public/TablePagination";
  import {ElMessageBox, ElMessage} from 'element-plus'
  import {delMediaFromPackage} from "@/api/package/package";
  import MediaDialog from "../components/media/MediaDialog";

  export default {
    name: "contentProject",
    components: {Search, Delete, TablePagination, Plus, MediaDialog},
    setup() {
      const route = useRoute()
      const store = useStore()
      const router = useRouter()
      const query = route.query
      const queryList = reactive({
        page: 1,
        pagesize: 25,
        ifext: 1,
        keyword: undefined,
        catid: undefined,
        mediatypes: [],
        packageid: undefined
      })
      const mediatypeList = ref([])
      const mediatypeObj = reactive({})
      // const categoryList = ref([])
      const isloading = ref(false)
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const deleteMediaData = reactive({
        packageid: undefined,
        mediaids: []
      })
      const currentCorpid = store.getters.corpinfo.corpid
      const mediaDataRef = ref(null)
      const corpPartnerObj = reactive({})
      const imgSrcList = ref([])
      const selectedMediatype = ref('')
      /** 添加媒资相关组件开始 **/
      const packageid = ref(0)
      const addMediaDialogVisible = ref(false)
      /** 添加媒资相关组件结束 **/

      const initialIndex = computed(() => {
        return (viewurl) => {
          return imgSrcList.value.findIndex(d => d == viewurl)
        }
      })

      /** 获取媒资类型列表 **/
      const getMediaTypeList = () => {
        getMediaTYpe().then(response => {
          if (response.errcode == 0) {
            mediatypeList.value = response.data
            mediatypeList.value.forEach(row => {
              mediatypeObj[row.mediatype] = row.name
            })
          }
        })
      }
      /** 获取媒资一级分类列表 **/
      /*const getCategoryList = () => {
        getCategories({mediatype: selectedMediatype.value, page: 1, pagesize: 10000}).then(response => {
          if (response.errcode == 0) {
            categoryList.value = response.data.list
          }
          console.log(response);
        })
      }*/
      /** 获取媒资列表 **/
      const getMediaList = () => {
        isloading.value = true
        getSearchMediaList(queryList).then(response => {
          isloading.value = false
          if (response.errcode == 0) {
            const {total, lists} = response.data
            tableData.total = total
            tableData.listData = lists
            imgSrcList.value = []
            nextTick(() => {
              tableData.listData.forEach(row => {
                if (row.covers && row.covers.length > 0) {
                  imgSrcList.value.push(row.covers[0].viewurl)
                }
              })
            })
          }
        })
      }
      /** 搜索建议 **/
      const handleMediaSearchSuggest = async (queryString, resolve) => {
        const query = {
          ifext: 1,
          packageid: route.query.packageid,
          prefix: queryString
        }
        const suggestionData = ref([])
        await mediaSearchSuggest(query).then(response => {
          if (response.errcode == 0) {
            suggestionData.value = response.data.lists
          }
        })
        resolve(suggestionData.value)
      }
      /** 检索媒资 **/
      const handleFilterMedia = () => {
        queryList.page = 1
        getMediaList()
      }
      /** 选择媒资 **/
      const handleSelectMedia = (selection, row) => {
        getSelectedMediaIds(row)
      }
      /** 判断媒资是否可选 **/
      const handleSelectMediaAble = (row) => {
        return currentCorpid == row.corpid
      }
      /** 全选媒资 **/
      const handleSelectAllMedia = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (!deleteMediaData.mediaids.includes(row.mediaid)) {
              deleteMediaData.mediaids.push(row.mediaid)
            }
          })
        } else {
          deleteMediaData.mediaids = []
        }
      }
      /** 点击行选择媒资 **/
      const handleClickRowMedia = (row) => {
        if (currentCorpid == row.corpid) {
          getSelectedMediaIds(row)
        }
        if (deleteMediaData.mediaids.includes(row.mediaid)) {
          mediaDataRef.value.toggleRowSelection(row, true)
        } else {
          mediaDataRef.value.toggleRowSelection(row, false)
        }
      }
      /** 获取选择的媒资ID **/
      const getSelectedMediaIds = (row) => {
        if (deleteMediaData.mediaids.includes(row.mediaid)) {
          const index = deleteMediaData.mediaids.findIndex(d => d == row.mediaid)
          deleteMediaData.mediaids.splice(index, 1)
        } else {
          deleteMediaData.mediaids.push(row.mediaid)
        }
      }
      /** 获取合作企业列表 **/
      const getCorpPartnerList = () => {
        getCorpPartner({partnertype: 0, corpid: currentCorpid}).then(response => {
          if (response.errcode == 0) {
            response.data.list.forEach(function (v) {
              corpPartnerObj[v.corpid] = v.corpname
            })
          }
        })
      }
      /** 切换媒资类型 **/
      const handleSelectMediatype = () => {
        queryList.page = 1
        if (selectedMediatype.value) {
          queryList.mediatypes = [selectedMediatype.value]
        } else {
          queryList.mediatypes = []
        }
        getMediaList()
      }
      /** 媒资详情 **/
      const handleToMediaDetail = (row) => {
        console.log(row);
        query.mediatype = row.mediatype
        query.mediaid = row.mediaid
        router.push({path: '/package/contentproject/media/detail', query: query})
      }
      /** 单条删除媒资 **/
      const handleDeleteMedia = (row) => {
        ElMessageBox.confirm('确定要删除媒资 ' + row.name + ' 吗？', '删除媒资', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          deleteMediaData.mediaids = [row.mediaid]
          doDeletePackageMedia()
        }).catch(() => {})
      }
      /** 批量删除媒资 **/
      const batchDeleteMedias = () => {
        if (deleteMediaData.mediaids.length <= 0) {
          ElMessage({type: 'warning', message: '请选择要删除的媒资', duration: 2000})
        } else {
          ElMessageBox.confirm('确定要删除媒资吗？', '删除媒资', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            doDeletePackageMedia()
          }).catch(() => {})
        }
      }
      /** 提交删除媒资请求 **/
      const doDeletePackageMedia = () => {
        deleteMediaData.packageid = parseInt(query.packageid)
        delMediaFromPackage(deleteMediaData).then(response => {
          if (response.errcode == 0) {
            ElMessage({type: 'success', message: response.msg, duration: 2000})
            getMediaList()
          }
        })
      }
      /** 添加媒资 **/
      const handleAddMedias = () => {
        packageid.value = parseInt(query.packageid)
        addMediaDialogVisible.value = true
      }
      /** 关闭添加媒资弹框 **/
      const cancelDialog = () => {
        addMediaDialogVisible.value = false
        getMediaList()
      }

      const init = () => {
        getMediaTypeList()
        queryList.packageid = query.packageid
        getMediaList()
        getCorpPartnerList()
      }
      init()

      return {
        queryList,
        init,
        mediatypeObj,
        mediatypeList,
        // categoryList,
        handleMediaSearchSuggest,
        handleFilterMedia,
        isloading,
        tableData,
        handleSelectMedia,
        handleSelectAllMedia,
        handleClickRowMedia,
        mediaDataRef,
        handleSelectMediaAble,
        currentCorpid,
        corpPartnerObj,
        initialIndex,
        imgSrcList,
        handleSelectMediatype,
        selectedMediatype,
        getMediaList,
        handleToMediaDetail,
        handleDeleteMedia,
        batchDeleteMedias,
        handleAddMedias,
        addMediaDialogVisible,
        packageid,
        cancelDialog
      }
    }
  }
</script>

<style>
  em{
    color: red;
    font-style: normal;
  }
</style>
